<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库编号" prop="outboundId">
        <el-input
          v-model="queryParams.outboundId"
          placeholder="请输入出库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库编号" prop="warehousing">
        <el-input
          v-model="queryParams.warehousing"
          placeholder="请输入入库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库状态" prop="outboundStatus">
        <el-select v-model="queryParams.outboundStatus" placeholder="请选择出库状态" clearable>
          <el-option
            v-for="dict in dict.type.outbound_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作员" prop="loginAccount">
        <el-input
          v-model="queryParams.loginAccount"
          placeholder="请输入操作员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库时间" prop="outboundTime">
        <el-date-picker clearable
                        v-model="queryParams.outboundTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择出库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:outbound:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="single"
          @click="generationList"
          v-hasPermi="['system:outbound:edit']"
        >生成拣货单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:outbound:edit']"
        >出库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:outbound:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:outbound:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outboundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="出库编号" align="center" prop="outboundId" />
      <el-table-column label="入库编号" align="center" prop="warehousing" />
      <el-table-column label="订单编号" align="center" prop="orderNumber" />
      <el-table-column label="出库状态" align="center" prop="outboundStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.outbound_status" :value="scope.row.outboundStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="userName" />
      <el-table-column label="操作员" align="center" prop="loginAccount" />
      <el-table-column label="出库时间" align="center" prop="outboundTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="generationList(scope.row)"
            v-hasPermi="['system:outbound:edit']"
          >生成</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:outbound:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出库编号" prop="outboundId">
          <el-input v-model="form.outboundId" placeholder="请输入出库编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="入库编号" prop="warehousing">
          <el-input v-model="form.warehousing" placeholder="请输入入库编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="出库状态" prop="outboundStatus">
          <el-select v-model="form.outboundStatus" placeholder="请选择出库状态">
            <el-option
              v-for="dict in dict.type.outbound_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
              :disabled="true"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入客户名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="操作员" prop="loginAccount">
          <el-input v-model="form.loginAccount" placeholder="请输入操作员" :disabled="true"/>
        </el-form-item>
        <el-form-item label="出库时间" prop="outboundTime">
          <el-date-picker clearable
                          v-model="form.outboundTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出库时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutbound, getOutbound, delOutbound, addOutbound, updateOutbound } from "@/api/system/outbound";
import {addList, listList, updateList} from "@/api/system/list";
import {addSending} from "@/api/system/sending";
import {listInfo, updateInfo} from "@/api/system/info";
import {addOrderlog} from "@/api/system/orderlog";

export default {
  name: "Outbound",
  dicts: ['outbound_status'],
  data() {
    return {
      //订单单列表
      orderList: [],
      //拣货单列表
      pickingList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库管理表格数据
      outboundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outboundId: null,
        warehousing: null,
        orderNumber: null,
        outboundStatus: null,
        userName: null,
        loginAccount: null,
        outboundTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        outboundId: [
          { required: true, message: "出库编号不能为空", trigger: "blur" }
        ],
        warehousing: [
          { required: true, message: "入库编号不能为空", trigger: "blur" }
        ],
        orderNumber: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        outboundStatus: [
          { required: true, message: "出库状态不能为空", trigger: "change" }
        ],
        userName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        loginAccount: [
          { required: true, message: "操作员不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询出库管理列表 */
    getList() {
      this.loading = true;
      listOutbound(this.queryParams).then(response => {
        this.outboundList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      listList().then(res => {
        this.pickingList = res.rows;
      });

      listInfo().then(res => {
        this.orderList = res.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        outboundId: null,
        warehousing: null,
        orderNumber: null,
        outboundStatus: null,
        userName: null,
        loginAccount: null,
        outboundTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出库管理";
    },
    /** 生成拣货单按钮操作 */
    generationList(row) {
      this.reset();
      const id = row.id || this.ids
      getOutbound(id).then(response => {
        this.form = response.data;
        //未出库才能生成拣货单
        if(this.form.outboundStatus === 2 || this.form.outboundStatus === 0){
          this.$modal.msgWarning("该订单已生成拣货单");
        }else{
          const DataForm = {
            outboundId :this.form.outboundId,
            orderNumber: this.form.orderNumber,
            outboundStatus: this.form.outboundStatus,
            // 以下字段不在 outList 中，根据需求补充默认值或留空
            orderCreateTime: null,   // 假设需要后续补充或留空
            orderType: null         // 假设需要后续补充或留空
          };
          addList(DataForm).then(response => {
            this.$modal.msgSuccess("生成拣货单成功");
            this.form.outboundStatus = 2;
            updateOutbound(this.form);
            // this.open = false;
            this.getList();
          });
          // this.open = true;
          // this.title = "修改出库管理";
        }

      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOutbound(id).then(response => {
        this.form = response.data;
        if(this.form.outboundStatus === 1){
          this.$modal.msgWarning("请先生成拣货单");
        } else if(this.form.outboundStatus === 0){
          this.$modal.msgWarning("该订单已出库");
        } else {
          this.form.outboundStatus = 0;
          this.form.loginAccount = this.$store.state.user.name;//操作员
          //出库时间

          this.open = true;
          this.title = "新增出库";
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOutbound(this.form).then(response => {

              //查询pickingList里为当前表单订单的记录   更新拣货单管理的订单出库状态
              this.pickingList.forEach((item, index) => {
                if(item.outboundId === this.form.outboundId){
                  const DataForm = {
                    id: item.id,
                    outboundId: item.outboundId,
                    orderNumber: item.orderNumber,
                    orderCreateTime: item.orderCreateTime,
                    orderType: item.orderType,
                    outboundStatus: 0
                  };
                  updateList(DataForm);
                }

              });

              //往申请寄件添加一条记录
              const sendingForm = {
                id: this.form.id,
                sendId: null,
                outboundId: this.form.outboundId,
                orderNumber: this.form.orderNumber,
                sendStatus: 1,
                sendTime: null,
                loginAccount: null,
                userName: this.form.userName
              };
              // 动态生成 sendId：sq + 当天日期（无斜杠） + id
              const today = new Date();
              const year = today.getFullYear();
              const month = today.getMonth() + 1;  // 月份从 0 开始，需 +1
              const day = today.getDate();

              // 拼接日期（格式如 20240327，无斜杠）
              const datePart = `${year}${month}${day}`;
              sendingForm.sendId = `sq${datePart}${sendingForm.id}`;
              addSending(sendingForm);

              this.orderList.forEach((item, index) => {
                if(item.orderNumber === this.form.orderNumber){
                  const orderForm = {
                    id: item.id,
                    orderNumber: item.orderNumber,
                    orderType: item.orderType,
                    orderStatus: item.orderStatus,
                    orderCreateTime: item.orderCreateTime,
                    storeStatus: item.storeStatus,
                    storeTime: item.storeTime,
                    packStatus: this.form.outboundStatus,//打包
                    packTime: this.form.outboundTime,
                    outboundStatus: this.form.outboundStatus,//出库
                    outboundTime: this.form.outboundTime,
                    stocktakingStatus: item.stocktakingStatus,//盘点状态
                    stocktakingTime: item.stocktakingTime,
                    sendStatus: item.sendStatus,
                    sendTime: item.sendTime,
                    userName: item.userName
                  };
                  updateInfo(orderForm);
                }

              });

              const logForm = {
                id: null,
                orderNumber: this.form.orderNumber,
                operateType: 12,
                operateTime: null,
                userAccount: this.$store.state.user.name,
                userName: this.form.userName,
                commName: null,
                stockTrackingnumber: null
              };

              // 生成符合数据库 datetime 格式的时间字符串（本地时区，格式如 "2024-03-29 15:30:45"）
              const now = new Date();
              const yearOne = now.getFullYear();
              const monthOne = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零（3 → "03"）
              const dayOne = String(now.getDate()).padStart(2, '0');
              const hours = String(now.getHours()).padStart(2, '0');
              const minutes = String(now.getMinutes()).padStart(2, '0');
              const seconds = String(now.getSeconds()).padStart(2, '0');

              logForm.operateTime = `${yearOne}-${monthOne}-${dayOne} ${hours}:${minutes}:${seconds}`;

              addOrderlog(logForm);


              this.$modal.msgSuccess("出库成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutbound(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除出库管理编号为"' + ids + '"的数据项？').then(function() {
        return delOutbound(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/outbound/export', {
        ...this.queryParams
      }, `outbound_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
